# -*- coding: utf-8 -*-
"""
django logging的配置
"""
import os
import logging
from logging.handlers import TimedRotatingFileHandler, RotatingFileHandler

LOGS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'logs')
format01 = '%(asctime)s  %(levelname)s %(name)s pid:%(process)d %(filename)s:%(lineno)d  %(message)s'
format02 = '%(asctime)s  %(levelname)s %(name)s pid:%(process)d %(pathname)s:%(lineno)d  %(message)s'


def create_log_file(_dir, filename):
    log_dir_path = os.path.join(LOGS_DIR, _dir)
    if not os.path.exists(log_dir_path):
        os.makedirs(log_dir_path, 0o777)
    return os.path.join(log_dir_path, filename)


def get_file_handler(_dir, filename, level='DEBUG'):
    """返回一个以文件大小切割的循环日志配置"""
    filename = create_log_file(_dir, filename)
    return {
        'level': level,
        'class': 'logging.handlers.RotatingFileHandler',
        'maxBytes': 1024 * 1024 * 5,
        'formatter': 'format01',
        'filters': ['require_debug_false'],
        'filename': filename,
        'encoding': 'utf-8',
        'backupCount': 3,
    }


def get_date_file_handler(_dir, filename, level='DEBUG'):
    """返回一个以日切割的循环日志配置"""
    filename = create_log_file(_dir, filename)
    return {
        'level': level,
        'class': 'logging.handlers.TimedRotatingFileHandler',
        'formatter': 'format01',
        'filters': ['require_debug_false'],
        'filename': filename,
        'when': 'D',
        'interval': 1,
        'encoding': 'utf-8',
        'backupCount': 30,
    }


def getLogger(name, rotation=1, level='INFO'):
    """
     自定义log函数,需传入自定义logger名
    :param name: logger名，默认日志名为 name.log
    :param rotation: 日志切割方式，1按时间，2按大小, 其他不分割
    :param level: 日志准入等级
    """
    filename = create_log_file('self', (name + '.log'))
    logger = logging.getLogger(name)
    logger.setLevel(level=level)
    logger.propagate = False
    if rotation == 1:
        handler = TimedRotatingFileHandler(filename, when='D', backupCount=10, encoding='utf-8')
    elif rotation == 2:
        handler = RotatingFileHandler(filename, maxBytes=1024 * 1024 * 5, backupCount=2, encoding='utf-8')
    else:
        handler = logging.FileHandler(filename, encoding='utf-8')
    handler.setLevel(level=level)
    handler.setFormatter(logging.Formatter(format01))
    logger.addHandler(handler)
    return logger


LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse',
        },
    },

    'handlers': {
        # 'mail_admins': {
        # 发邮件通知，未启用
        #     'level': 'ERROR',
        #     'class': 'django.utils.log.AdminEmailHandler',
        # },
        'console': {
            # debug模式时控制台输出
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'filters': ['require_debug_true'],
            'formatter': 'format01'
        },
        'default_handler': get_file_handler('default', 'info.log', 'INFO'),
        # 'request_handler': get_date_file_handler('default', 'request.log', 'INFO'),
        'error_handler': get_date_file_handler('default', 'error.log', 'ERROR'),
        'scripts_handler': get_file_handler('scripts', 'scripts.log'),
    },

    'loggers': {
        '': {  # 空缺时默认log
            'handlers': ['default_handler', 'console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        # 'django': {  # 默认request log
        #     'handlers': ['request_handler', 'console'],
        #     'level': 'INFO',
        #     'propagate': False
        # },
        'django.request': {  # error log
            'handlers': ['error_handler'],
            'level': 'ERROR',
            'propagate': True,
        },
        # 'django.db.backends': {   # 控制台输出打印sql 语句
        #         'handlers': ['console'],
        #         'level': 'DEBUG',
        #         'propagate': True,
        #     },
        'scripts': {  # 脚本日志
            'qualname': 'scripts',
            'level': 'INFO',
            'handlers': ['scripts_handler'],
            'propagate': False
        },
    },

    'formatters': {
        'format01': {
            'format': format01,
            'datefmt': '[%Y-%m-%d %H:%M:%S]'
        },
        'format02': {
            'format': format02,
            'datefmt': '[%Y-%m-%d %H:%M:%S]'
        }
    }
}


# 错误邮件配置，未启用
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_HOST = 'smtp-mail.outlook.com'
# EMAIL_PORT = 25
# EMAIL_HOST_USER = 'ylyhyunying@outlook.com'
# EMAIL_HOST_PASSWORD = 'ylyh*yunying'
# SERVER_EMAIL = EMAIL_HOST_USER
# EMAIL_FROM = 'YLYH<ylyhyunying@outlook.com>'
# DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
